package com.daoshu.mds.message.controller;


import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Optional;

import com.daoshu.mds.dispatch.entity.MicroGroupBusiness;
import com.daoshu.mds.message.service.*;
import io.swagger.annotations.ApiImplicitParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.daoshu.component.exception.BusinessException;
import com.daoshu.component.page.PageConstants;
import com.daoshu.component.response.ResponseCallBack;
import com.daoshu.component.response.ResponseCriteria;
import com.daoshu.component.response.ResponseInfo;
import com.daoshu.mds.constants.MessageType;
import com.daoshu.mds.dispatch.bo.MicroGroupBO;
import com.daoshu.mds.dispatch.entity.MicroGroupEntity;
import com.daoshu.mds.dispatch.entity.MicroGroupMemberEntity;
import com.daoshu.mds.dispatch.entity.MicroGroupMessageEntity;
import com.daoshu.mds.dispatch.qo.MicroGroupQO;
import com.daoshu.mds.dispatch.qo.MicroMessageQO;
import com.daoshu.system.bo.AccountBo;
import com.daoshu.system.utils.RequestUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * <p>
 *  微群前端控制器
 * </p>
 *
 * @author zhaoyanjiang
 * @since 2018-09-10
 */
@Api(value="微群接口",description="微群接口")
@RestController
@RequestMapping("/mds")
public class MicroGroupController {
	
	@Autowired private IMicroGroupMemberService microGroupMemberService;
	@Autowired private IMicroGroupMessageService microGroupMessageService;
	@Autowired private IPersonGroupService personGroupService;
	@Autowired private IMicroGroupService microGroupService;
	@Autowired private IMessageService messageService;
	@Autowired private RequestUtils userUtil;

	@Autowired
	private IMicroGroupBusinessService microGroupBusinessService;
	
	@ApiOperation(value="新增微群",notes="新增微群")
	@RequestMapping(value="/microGroup",method=RequestMethod.POST)
	public ResponseInfo addGeneralConcats(@RequestBody final MicroGroupBO bo){
		return new ResponseCallBack() {
			@Override
			public void execute(ResponseCriteria criteria, Object... obj) {
				criteria.addSingleResult(microGroupService.addMicroGroup(bo));
			}
		}.sendRequest();
	}
	
	@ApiOperation(value = "修改微群名称", notes = "修改微群名称")
	@PostMapping(value = "/updateMicroGroupTitle")
	public ResponseInfo updateMicroGroupTitle(@RequestBody final MicroGroupBO bo) {
		return new ResponseCallBack() {
			public void execute(ResponseCriteria criteria, Object... obj) {
				MicroGroupEntity entity = new MicroGroupEntity();
				BeanUtils.copyProperties(bo, entity);
				entity.setLastMessageUpdateTime(new Date());
				criteria.addSingleResult(microGroupService.updateById(entity));
			}
		}.sendRequest();
	}
	@ApiOperation(value="查询微群重要消息记录",notes="查询微群重要消息记录")
	@RequestMapping(value="/microGroup/important/message/page",method=RequestMethod.POST)
	public ResponseInfo queryImportMicroMessage(@RequestBody final MicroMessageQO qo){
		return new ResponseCallBack() {
			@Override
			public void execute(ResponseCriteria criteria, Object... obj) {
				IPage<MicroGroupMessageEntity> page = microGroupMessageService.queryImportMessage(qo);
				criteria.addMapResult(PageConstants.PAGE_RESULT_NAME, page.getRecords());
				criteria.addMapResult(PageConstants.PAGE_RESULT_COUNT, page.getTotal());
			}
		}.sendRequest();
	}
	@ApiOperation(value="查询微群消息记录",notes="查询微群消息记录")
	@RequestMapping(value="/microGroup/message/list",method=RequestMethod.POST)
	public ResponseInfo queryMicroMessage(@RequestBody final MicroMessageQO qo){
		return new ResponseCallBack() {
			@Override
			public void execute(ResponseCriteria criteria, Object... obj) {
				IPage<MicroGroupMessageEntity> page = microGroupMessageService.queryMicroMessage(qo);
				microGroupMemberService.setReadTime(qo.getMicroGroupId(), userUtil.getCurrentUser().getPersonId(),false);
				personGroupService.saveOrUpd(qo.getMicroGroupId(), userUtil.getCurrentUser().getPersonId());
				criteria.addMapResult(PageConstants.PAGE_RESULT_NAME, page.getRecords());
				criteria.addMapResult(PageConstants.PAGE_RESULT_COUNT, page.getTotal());
			}
		}.sendRequest();
	}
	
	@ApiOperation(value="查询微群列表",notes="查询微群列表")
	@RequestMapping(value="/microGroup/list",method=RequestMethod.POST)
	public ResponseInfo queryMicroGroupInPerson(@RequestBody final MicroGroupQO qo){
		return new ResponseCallBack() {
			@Override
			public void execute(ResponseCriteria criteria, Object... obj) {
				IPage<MicroGroupBO> page = microGroupService.queryMicroGroupInPerson(qo);
				criteria.addMapResult(PageConstants.PAGE_RESULT_NAME, page.getRecords());
				criteria.addMapResult(PageConstants.PAGE_RESULT_COUNT, page.getTotal());
			}
		}.sendRequest();
	}
	
	@ApiOperation(value="发送微群消息",notes="发送微群消息")
	@RequestMapping(value="/microGroup/message",method=RequestMethod.POST)
	public ResponseInfo addMessage(@RequestBody final MicroGroupMessageEntity message){
		return new ResponseCallBack() {
			@Override
			public void execute(ResponseCriteria criteria, Object... obj) {
				boolean flag = microGroupMessageService.sendMicroGroupMessage(message);
				criteria.addSingleResult(flag?"发送成功":"发送失败");
			}
		}.sendRequest();
	}
	
	@ApiOperation(value="获取未读消息数量",notes="获取未读消息数量")
	@RequestMapping(value="/microGroup/message/count",method=RequestMethod.GET)
	public ResponseInfo getUnreadMessage(@RequestParam(required=false) String groupId, @RequestParam String personId){
		return new ResponseCallBack() {
			@Override
			public void execute(ResponseCriteria criteria, Object... obj) {
				Integer count = microGroupMessageService.getUnreadMessage(groupId, personId);
				criteria.addSingleResult(count);
			}
		}.sendRequest();
	}
	@ApiOperation(value="获取微群成员数量",notes="获取成员数量")
	@RequestMapping(value="/microGroup/members/count",method=RequestMethod.GET)
	public ResponseInfo getMembersCount(@RequestParam String groupId){
		return new ResponseCallBack() {
			@Override
			public void execute(ResponseCriteria criteria, Object... obj) {
				Integer count = microGroupMemberService.count(new QueryWrapper<MicroGroupMemberEntity>().eq("micro_group_id_", groupId));
				criteria.addSingleResult(count);
			}
		}.sendRequest();
	}
	@ApiOperation(value="退出微群",notes="退出微群")
	@RequestMapping(value="/microGroup/members",method=RequestMethod.GET)
	public ResponseInfo exitMicro(@RequestParam String groupId, @RequestParam(required = false) String personIds, @RequestParam(required = false) String personNames){
		return new ResponseCallBack() {
			@SuppressWarnings("unused")
			@Override
			public void execute(ResponseCriteria criteria, Object... obj) {
				MicroGroupMessageEntity entity = new MicroGroupMessageEntity();
				String deleteIds = "";
				AccountBo user = userUtil.getCurrentUser();
				MicroGroupEntity group = Optional.ofNullable(microGroupService.getById(groupId)).orElseThrow(()->{
					return new BusinessException(500, "此微群不存在，请确认");
				});
//				if("1".equals(group.getGroupType())) { // 单聊删除
//					microGroupService.deleteMicroGroup(groupId);
//					return;
//				}
				if (StringUtils.isEmpty(personIds)) {
					deleteIds = user.getPersonBo().getId();
					entity.setContent(user.getPersonBo().getName() + " 退出群聊");
				} else {
					deleteIds = personIds;
					entity.setContent(user.getPersonBo().getName() + " 将 " + personNames + " 移出群聊");
				}
				List<String> ids = Arrays.asList(deleteIds.split(","));
				List<MicroGroupMemberEntity> members = microGroupMemberService.list(new QueryWrapper<MicroGroupMemberEntity>().lambda()
						.in(MicroGroupMemberEntity::getPersonId, ids)
						.eq(MicroGroupMemberEntity::getMicroGroupId, groupId));
				if(members.size()!=ids.size()) {
					throw new BusinessException(500, "有成员不在此微群中，请确认");
				}
				microGroupMemberService.remove(new QueryWrapper<MicroGroupMemberEntity>().in("person_id_", ids).eq("micro_group_id_", groupId));
				entity.setCreateName("系统消息");
				entity.setMicroGroupId(groupId);
				entity.setCreateId(user.getPersonBo().getId());
				entity.setType(MessageType.SYSTEM_INFO.getType());
				entity.setCreateTime(new Date());
				messageService.sendMessage(entity);
				criteria.addSingleResult(entity);
			}
		}.sendRequest();
	}
	@ApiOperation(value="删除微群",notes="删除微群")
	@RequestMapping(value="/microGroup/{id}",method=RequestMethod.DELETE)
	public ResponseInfo getUnreadMessage(@PathVariable("id") String id){
		return new ResponseCallBack() {
			@Override
			public void execute(ResponseCriteria criteria, Object... obj) {
				microGroupService.deleteMicroGroup(id);
				criteria.addSingleResult("删除成功");
			}
		}.sendRequest();
	}
	
	@ApiOperation(value="更新读取时间",notes="更新读取时间")
	@RequestMapping(value="/microGroup/message/readTime",method=RequestMethod.PUT)
	public ResponseInfo setReadTime(@RequestParam String groupId){
		return new ResponseCallBack() {
			@Override
			public void execute(ResponseCriteria criteria, Object... obj) {
				microGroupMemberService.setReadTime(groupId, userUtil.getCurrentUser().getPersonId(),false);
				criteria.addSingleResult("更新成功");
			}
		}.sendRequest();
	}
	@ApiOperation(value="更新重要消息读取时间",notes="更新重要消息读取时间")
	@RequestMapping(value="/microGroup/message/important/readTime",method=RequestMethod.PUT)
	public ResponseInfo setImportReadTime(@RequestParam String messageId){
		return new ResponseCallBack() {
			@Override
			public void execute(ResponseCriteria criteria, Object... obj) {
				microGroupMemberService.setReadTime(messageId, userUtil.getCurrentUser().getPersonId(),true);
				criteria.addSingleResult("更新成功");
			}
		}.sendRequest();
	}
	@ApiOperation(value="添加成员",notes="添加成员")
	@RequestMapping(value="/microGroup/members",method=RequestMethod.POST)
	public ResponseInfo addMembers(@RequestBody List<MicroGroupMemberEntity> members){
		return new ResponseCallBack() {
			@Override
			public void execute(ResponseCriteria criteria, Object... obj) {
				microGroupMemberService.addMembers(members);
				criteria.addSingleResult("添加成功");
			}
		}.sendRequest();
	}
	
	@ApiOperation(value="获取微群成员列表",notes="获取微群成员列表")
	@RequestMapping(value="/microGroup/members/page",method=RequestMethod.POST)
	public ResponseInfo addMembers(@RequestBody MicroGroupQO qo){
		return new ResponseCallBack() {
			@Override
			public void execute(ResponseCriteria criteria, Object... obj) {
				IPage<MicroGroupMemberEntity> page = microGroupMemberService.queryMember(qo);
				criteria.addMapResult(PageConstants.PAGE_RESULT_NAME, page.getRecords());
				criteria.addMapResult(PageConstants.PAGE_RESULT_COUNT, page.getTotal());
			}
		}.sendRequest();
	}
	@ApiOperation(value="查询会议聊天内容",notes="查询会议聊天列表")
	@RequestMapping(value="/messages/page",method=RequestMethod.POST)
	public ResponseInfo queryConfienceMessage(@RequestBody final MicroMessageQO qo){
		return new ResponseCallBack() {
			@Override
			public void execute(ResponseCriteria criteria, Object... obj) {
				IPage<MicroGroupMessageEntity> page = microGroupMessageService.queryConfienceMessage(qo);
				criteria.addMapResult(PageConstants.PAGE_RESULT_NAME, page.getRecords());
				criteria.addMapResult(PageConstants.PAGE_RESULT_COUNT, page.getTotal());
			}
		}.sendRequest();
	}
	
	@ApiOperation(value = "离开聊天页面，更新未读", notes = "离开聊天页面，更新未读消息")
	@GetMapping(value = "/leavePage")
	public ResponseInfo leavePage() {
		return new ResponseCallBack() {
			public void execute(ResponseCriteria criteria, Object... obj) {
				personGroupService.updateReadTimeOffline(userUtil.getCurrentUser().getPersonId());
				//criteria.addSingleResult(new Object());
			}
		}.sendRequest();
	}
	@ApiOperation(value = "设置重要消息", notes = "设置重要消息")
	@GetMapping(value = "/messages/important/{messageId}")
	public ResponseInfo setupImportMessage(@PathVariable(value="messageId") String messageId) {
		return new ResponseCallBack() {
			public void execute(ResponseCriteria criteria, Object... obj) {
				microGroupMessageService.setupImportMessage(messageId);
			}
		}.sendRequest();
	}

	/**
	 * 查询微群重要消息记录历史记录
	 *
	 * @param microMessageQO
	 * @return
	 */
	@ApiOperation(value="查询微群重要消息记录历史记录", notes="查询微群重要消息记录历史记录")
	@ApiImplicitParam(name = "microMessageQO", value = "微群信息对象bo", required = false, dataType = "MicroMessageQO", paramType = "query")
	@PostMapping(value="/microGroup/important/historyMessage/page")
	public ResponseInfo queryImportHistoryMicroMessage(MicroMessageQO microMessageQO) {
		return new ResponseCallBack() {
			@Override
			public void execute(ResponseCriteria criteria, Object... obj) {
				IPage<MicroGroupMessageEntity> page = microGroupMessageService.queryImportHistoryMicroMessage(microMessageQO);
				criteria.addMapResult(PageConstants.PAGE_RESULT_NAME, page.getRecords());
				criteria.addMapResult(PageConstants.PAGE_RESULT_COUNT, page.getTotal());
			}
		}.sendRequest();
	}

    /**
     * 取消重要消息设置
     *
     * @param messageId 消息id
     * @return
     */
	@ApiOperation(value = "取消重要消息设置", notes = "取消重要消息设置")
	@GetMapping(value = "/messages/cancalSettingImportant/{messageId}")
	public ResponseInfo cancalSettingImportant(@PathVariable(value="messageId") String messageId) {
		return new ResponseCallBack() {
			public void execute(ResponseCriteria criteria, Object... obj) {
				microGroupMessageService.cancalSettingImportant(messageId);
			}
		}.sendRequest();
	}

	/**
	 * 根据微群关联业务对象查询列表
	 *
	 * @param microGroupBusiness
	 * @return
	 */
	@ApiOperation(value = "根据微群关联业务对象查询列表", notes = "根据微群关联业务对象查询列表")
	@PostMapping(value = "/microGroup/businessListByMicroGroupBusiness")
	public ResponseInfo businessListByMicroGroupBusiness(MicroGroupBusiness microGroupBusiness) {
		return new ResponseCallBack() {
			@Override
			public void execute(ResponseCriteria responseCriteria, Object... objects) {
				QueryWrapper<MicroGroupBusiness> queryWrapper = new QueryWrapper<>();
				queryWrapper.setEntity(microGroupBusiness);
				List<MicroGroupBusiness> microGroupBusinesses = microGroupBusinessService.list(queryWrapper);
				responseCriteria.addSingleResult(microGroupBusinesses);
			}
		}.sendRequest();
	}

}
